'use client';

import { useQuery } from '@tanstack/react-query';
import { queryAllPost, queryPostStatistics, searchPost } from '@/services/api';
import type {
  IPagination,
  IPost,
  IPostStatistics,
  IQueryParams,
} from '@/interfaces';
import { formatDateTime, getSectionQueryParams } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Alert from '@/app/[locale]/alert/alert';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import Pagination from '@/app/[locale]/admin/common/pagination';
import useToast from '@/hooks/useToast';
import { type ChangeEvent, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import PostName from '@/app/[locale]/common/post/name';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function PostAdminPage(
  this: any,
  {
    source,
    translatedFields,
  }: {
    source: IPagination<IPost>;
    translatedFields: PrefixedTTranslatedFields<'postAdminPage'>;
  },
) {
  const { show } = useToast();
  const urlSearchParams = useSearchParams();
  const [params, setParams] = useState<IQueryParams>({
    page: 0,
    sectionId: getSectionQueryParams(urlSearchParams)?.id,
  });
  const [searchName, setSearchName] = useState('');
  const router = useRouter();

  const queryPostStatisticsQuery = useQuery(
    ['/forum', '/posts', '/statistics'],
    async () => {
      return (await queryPostStatistics()) as IPostStatistics;
    },
  );
  const queryAllPostQuery = useQuery(
    ['/forum', '/posts', params, searchName],
    async (context) => {
      if (searchName) {
        return (await searchPost({
          query: {
            ...(context.queryKey[2] as any),
            name: context.queryKey[3],
          },
        })) as IPagination<IPost>;
      } else {
        return (await queryAllPost({
          query: context.queryKey[2] as any,
        })) as IPagination<IPost>;
      }
    },
    {
      keepPreviousData: true,
      initialData: source,
    },
  );

  async function onClickCreate() {
    await router.push('/posts/new');
  }

  function onClickDetail(item: IPost) {
    router.push(`post/detail?id=${item.id}`);
  }

  function onClickUpdate(item: IPost) {
    router.push(`post/update?id=${item.id}`);
  }

  function onClickDelete(item: IPost) {
    router.push(`post/delete?id=${item.id}`);
  }

  function onClickPrevious() {
    const data = queryAllPostQuery.data;
    if (!data) {
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = queryAllPostQuery.data;
    if (!data) {
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  function onChangeSearch(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value;
    setSearchName(value.toLowerCase());
  }

  return (
    <div className="row g-4">
      <div className="col-12">
        <Box>
          <div className="card">
            <div className="card-body">
              <h6 className="card-subtitle mb-2 text-secondary">
                {translatedFields.count}
              </h6>
              <h5 className="card-title">
                {queryPostStatisticsQuery.data &&
                  queryPostStatisticsQuery.data.count}

                {queryPostStatisticsQuery.isError && (
                  <Alert
                    message={queryPostStatisticsQuery.error}
                    type="error"
                  />
                )}

                {queryPostStatisticsQuery.isLoading && <Spinner />}
              </h5>
            </div>
          </div>
        </Box>
      </div>
      <div className="col">
        <Box>
          <div className="card">
            <div className="card-header bg-transparent">
              <div className="row row-cols-auto justify-content-between g-2">
                <div className="col">
                  <div className="input-group">
                    <span className="input-group-text">
                      <i className="bi bi-search"></i>
                    </span>
                    <input
                      onChange={onChangeSearch}
                      type="search"
                      className="form-control"
                      placeholder={translatedFields.searchPlaceholder}
                    />
                  </div>
                </div>
                <div className="col"></div>
              </div>
            </div>
            <div className="card-body vstack gap-4">
              <div className="table-responsive">
                <table className="table table-hover align-middle">
                  <thead>
                    <tr className="text-nowrap">
                      <th scope="col" className="">
                        ID
                      </th>
                      <th scope="col" className="">
                        {translatedFields.name}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.reviewState}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.otherStates}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.sort}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.author}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.update}
                      </th>
                      <th scope="col" className=""></th>
                    </tr>
                  </thead>
                  <tbody>
                    {queryAllPostQuery.data.content.map((item) => {
                      return (
                        <tr key={item.id} className="text-nowrap">
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {item.id}
                          </td>
                          <td className="text-truncate">
                            <PostName
                              item={item}
                              isTable
                              isFwSemibold={false}
                            />
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {
                              translatedFields.REVIEW_STATE[
                                item.details!.reviewState
                              ]
                            }
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {(item.details!.otherStates.length === 0
                              ? ['DEFAULT']
                              : item.details!.otherStates
                            ).map(
                              (value) =>
                                (translatedFields as any).OTHER_STATE[value],
                            )}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {
                              (translatedFields as any).SORT_STATE[
                                item.details!.sortState
                              ]
                            }
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {`${item.creatorAlias} (ID. ${item.createdBy})`}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {formatDateTime(item.contentUpdatedOn)}
                          </td>
                          <td>
                            <div className="hstack gap-2">
                              <button
                                onClick={onClickUpdate.bind(this, item)}
                                className="btn btn-sm btn-light"
                                type="button"
                              >
                                <i className="bi bi-pencil me-2"></i>
                                {translatedFields.update}
                              </button>

                              <button
                                onClick={onClickDelete.bind(this, item)}
                                className="btn btn-sm btn-light text-danger"
                                type="button"
                              >
                                <i className="bi bi-trash me-2"></i>
                                {translatedFields.delete}
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {queryAllPostQuery.data.content.length === 0 && <Nodata />}

              <Pagination
                isShow={queryAllPostQuery.data.pageable.pages > 0}
                onPrevious={onClickPrevious}
                onNext={onClickNext}
                isPrevious={queryAllPostQuery.data.pageable.previous}
                isNext={queryAllPostQuery.data.pageable.next}
                translatedFields={translatedFields.pagination}
              />
            </div>
          </div>
        </Box>
      </div>
    </div>
  );
}
